//
//  SunForgetCodeVC.m
//  Xspcf
//
//  Created by sunshine on 16/10/18.
//  Copyright © 2016年 小小算盘. All rights reserved.
//

#import "SunForgetCodeVC.h"

@interface SunForgetCodeVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    UITextField *_validate;
    UITextField *_code;
    UIButton *_timeBtn;
    UIButton *_nextBtn;
    UIButton *_securityBtn;
    NSTimer *_timer;
    int _time;
}
@end

@implementation SunForgetCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BACKGROUND;
    self.title = @"找回密码";
    [self creatUI];
    // Do any additional setup after loading the view.
}

- (void)dealloc{
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)creatUI{
    UITableView *tb = [[UITableView alloc]init];
    [self.view addSubview:tb];
    tb.backgroundColor = WHITE;
    [tb lt_Top:SunEdgesMake(Y(32), 0, 0, Y(149)) to:nil save:YES];
    tb.delegate = self;
    tb.dataSource = self;
    tb.scrollEnabled = NO;
    _nextBtn = [[UIButton alloc]init];
    [self.view addSubview:_nextBtn];
    [_nextBtn lt_Top:SunEdgesMake(Y(70), X(15), X(15), Y(44)) to:tb save:YES];
    _nextBtn.clipsToBounds = YES;
    [_nextBtn setBackgroundColor:BLUE forState:UIControlStateNormal];
    [_nextBtn setBackgroundColor:[HXColor colorWithHexString:@"87CEFA"] forState:UIControlStateHighlighted];
    _nextBtn.layer.cornerRadius = 4;
    [_nextBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_nextBtn setTitleColor:WHITE forState:UIControlStateNormal];
    _nextBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    [_nextBtn addTarget:self action:@selector(gotoCheck) forControlEvents:UIControlEventTouchUpInside];
    _nextBtn.enabled = NO;
    UIView *line1 = [[UIView alloc]init];
    line1.backgroundColor = [UIColor colorWithHexString:@"dedede"];
    [self.view addSubview:line1];
    [line1 lt_Top:SunEdgesMake(0, 0, 0, 0.5) to:tb save:YES];
    UIView *line2 = [[UIView alloc]init];
    line2.backgroundColor = [UIColor colorWithHexString:@"dedede"];
    [self.view addSubview:line2];
    [line2 lt_Bottom:SunEdgesMake(0, 0, 0, 0.5) to:tb save:YES];
}

- (void)gotoCheck{
    [[Sun shareSun]showActivity:self];
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_CHANGECODE];
    NSDictionary *dic = @{@"password":_code.text,@"code":_validate.text,@"phone":self.phone};
    [HttpRequest postURL:url withParam:dic success:^(id requestDic, NSString *msg) {
        [[Sun shareSun]hideAll];
        [[Sun shareSun]showMsg:msg];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun]hideAll];
        [[Sun shareSun]showMsg:errorInfo];
    }];
}

- (void)getValidateCode{
    [_timeBtn setTitle:@"发送中" forState:UIControlStateNormal];
    [[Sun shareSun]showActivity:self];
    NSString *url = [NSString stringWithFormat:@"%@%@",KURL,API_CODE];
    NSDictionary *dic = @{@"phone":self.phone,@"type":@"2"};
    [HttpRequest postURL:url withParam:dic success:^(id requestDic, NSString *msg) {
        [[Sun shareSun]hideAll];
        [[Sun shareSun]showMsg:@"发送成功"];
        _time = 60;
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    } failure:^(NSString *errorInfo, int code) {
        [[Sun shareSun]hideAll];
        [[Sun shareSun]showMsg:errorInfo];
        _timeBtn.enabled=YES;
        [_timeBtn setTitle:@"获取验证" forState:UIControlStateNormal];
    }];
}

- (void)onTimer{
    _timeBtn.enabled=NO;
    if(_time == 0){
        _timeBtn.enabled=YES;
        [_timeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        [_timer invalidate];
        _timer = nil;
        _time = 60;
        return;
    }
    _time --;
    [_timeBtn setTitle:[NSString stringWithFormat:@"剩余%ds",_time] forState:UIControlStateNormal];
}

- (void)changeSecurity{
    if (_securityBtn.isSelected) {
        _securityBtn.selected = NO;
        _code.secureTextEntry = YES;
    }else{
        _securityBtn.selected = YES;
        _code.secureTextEntry = NO;
    }
}

#pragma mark tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return Y(50);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    switch (indexPath.row) {
        case 0:{
            cell.imageView.image = [UIImage imageNamed:@"login_phone"];
            UILabel *phone = [[UILabel alloc]init];
            [cell addSubview:phone];
            [phone lt_YcenterTo:nil save:YES];
            [phone lt_setLeft:X(60) to:nil save:YES];
            phone.textColor = BLACK;
            phone.font = [UIFont systemFontOfSize:16];
            phone.text = [[[self.phone substringToIndex:3]stringByAppendingString:@"****"]stringByAppendingString:[self.phone substringFromIndex:7]];
            break;
        }
        case 1:{
            cell.imageView.image = [UIImage imageNamed:@"login_validate"];
            _validate = [[UITextField alloc]init];
            [cell addSubview:_validate];
            [_validate lt_YcenterTo:nil save:YES];
            [_validate lt_setLeft:X(60) to:nil save:YES];
            [_validate lt_setWidth:X(230) save:YES];
            _validate.textColor = BLACK;
            _validate.font = [UIFont systemFontOfSize:16];
            _validate.placeholder = @"请输入验证码";
            _validate.keyboardType = UIKeyboardTypeNumberPad;
            _validate.clearButtonMode = UITextFieldViewModeWhileEditing;
            _validate.delegate = self;
            _validate.returnKeyType=UIReturnKeyDone;
            _timeBtn = [[UIButton alloc]init];
            [cell addSubview:_timeBtn];
            [_timeBtn lt_YcenterTo:nil save:YES];
            [_timeBtn lt_setRight:X(15) to:nil save:YES];
            _timeBtn.clipsToBounds = YES;
            _timeBtn.layer.cornerRadius = 3;
            [_timeBtn setBackgroundColor:RED forState:UIControlStateNormal];
            [_timeBtn setBackgroundColor:[HXColor colorWithHexString:@"FFB6C1"] forState:UIControlStateHighlighted];
            _timeBtn.titleLabel.font = [UIFont systemFontOfSize:12];
            _timeBtn.contentEdgeInsets = UIEdgeInsetsMake(4, 4, 4, 4);
            [_timeBtn setTitleColor:WHITE forState:UIControlStateNormal];
            [_timeBtn setTitle:@"获取验证" forState:UIControlStateNormal];
            [_timeBtn addTarget:self action:@selector(getValidateCode) forControlEvents:UIControlEventTouchUpInside];
            break;
        }
        case 2:{
            cell.imageView.image = [UIImage imageNamed:@"login_code"];
            _code = [[UITextField alloc]init];
            [cell addSubview:_code];
            [_code lt_YcenterTo:nil save:YES];
            [_code lt_setLeft:X(60) to:nil save:YES];
            [_code lt_setWidth:X(230) save:YES];
            _code.textColor = BLACK;
            _code.font = [UIFont systemFontOfSize:16];
            _code.placeholder = @"请设置6~16位登录密码";
            _code.clearButtonMode = UITextFieldViewModeWhileEditing;
            _code.returnKeyType=UIReturnKeyDone;
            _code.delegate = self;
            _code.secureTextEntry = YES;
            _securityBtn = [[UIButton alloc]init];
            [cell addSubview:_securityBtn];
            [_securityBtn lt_YcenterTo:nil save:YES];
            [_securityBtn lt_setRight:X(15) to:nil save:YES];
            [_securityBtn setImage:[UIImage imageNamed:@"login_security"] forState:UIControlStateNormal];
            [_securityBtn setImage:[UIImage imageNamed:@"login_unsecurity"] forState:UIControlStateSelected];
            [_securityBtn addTarget:self action:@selector(changeSecurity) forControlEvents:UIControlEventTouchUpInside];
            break;
        }
        default:
            break;
    }
    return cell;
}

#pragma mark textField
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    _nextBtn.enabled = NO;
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    _nextBtn.enabled = NO;
    if (textField == _validate) {
        if (_code.text.length >= 6 && _code.text.length <= 16) {
            if (textField.text.length >= 5 && string.length > 0) {
                _nextBtn.enabled = YES;
            }
        }
        if (textField.text.length == 6 && string.length > 0) {
            return NO;
        }
    }
    if (textField == _code) {
        if (_validate.text.length == 6) {
            if (string.length > 0 && textField.text.length >= 5 && textField.text.length <= 15) {
                _nextBtn.enabled = YES;
            }
            if (string.length <= 0 && textField.text.length >= 7 && textField.text.length <= 17) {
                _nextBtn.enabled = YES;
            }
        }
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
